<template>
  <basic-container :radius="0">
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 建</el-button>
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.terminal_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.terminal_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{ row }" slot="isOn">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="row.isOn"
          @change="handleSwitch(row)"
        >
        </el-switch>
      </template>
      <template slot-scope="scope" slot="menu">
        <!-- <el-button icon="el-icon-connection" size="small" type="text" @click.stop="delJB(scope.row)">终端解绑</el-button> -->
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row, scope.index)">编 辑</el-button>

      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 新建 -->
    <el-dialog
      :title="terminalDialog.text"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="terminalDialog.visible"
      v-if="terminalDialog.visible"
      :before-close="terminalDialogHandleClose"
      ref="terDialog"
    >
      <terminalDialog ref="terminalDialog" :terminalDialog="terminalDialog" :rpiNo="rpiNo" :terminalDForm="terminalDialogForm"/>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="() => { terminalDialog.visible = false; this.$refs['terminalDialog'].initEmpty();}">取 消</el-button>
        <el-button type="primary" v-preventClick @click="terminalDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-image-viewer
      style="z-index: 2048"
      v-if="payVoucherDialog"
      :on-close="()=>{ payVoucherDialog = false }"
      :url-list="[rqUrlImage]"
    ></el-image-viewer>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form :model="towPwdForm" ref="towPwdForm" label-width="0" class="demo-ruleForm">
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            { required: true,message: '二级密码不能为空', trigger: ['change','blur']},
            { pattern: /^[0-9]{6}$/, message: '二级密码由6位数字组成', trigger: ['change','blur']}
          ]"
          >
          <el-input show-password v-model.number="towPwdForm.towPwd" autocomplete="off" placeholder="输入二级密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
// import {
//   getTerminalPage,
//   getDetail,
//   addTerminal,
//   editTerminal,
//   incomingTerminalOn,
//   getRptNo,
//   getrpiNo,
//   getstoreNo,
//   getrpstNo
// } from "@/api/rb-core/terminal/terminal";
import {mapGetters} from "vuex";
import {getToken} from "@/util/auth";
import terminalDialog from "./terminalDialogSM";
// import { userHasInfo } from "@/api/rb-core/forgetPassword/forgetPassword";
import md5 from 'js-md5';
import { remove as del } from "@/api/rb-core/posinfo/terminal/taika";

export default {
  components: {
    terminalDialog
  },
  data() {
    return {
      payVoucherDialog: false,
      rqUrlImage: [],
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        labelWidth:100,
        addBtn: false,//取消表格 新建/添加
        editBtn:false,
        viewBtn:false,
        delBtn:false,
        viewTitle:'修 改',
        menuWidth: 100,
        // menu:false,
        column: [
          {
            label: "终端供应商",
            prop: "rpsName",
            type: "input",
            // sortable: true,
            display: false,
            width:120,
            overHidden:true
          },
          {
            label: "终端型号",
            prop: "rpmName",
            type: "input",
            display: false
          },
          {
            label: "终端编号",
            prop: "rtNo",
            type: "input",
            search: true,
            //sortable: true,
            overHidden: true,
            display: false,
          },
          {
            label: "终端简称",
            prop: "rtName",
            type: "input",
            search: true,
            overHidden: true,
            display: false
          },
        //   {
        //     label: "终端类型",
        //     prop: "rptName",
        //     type: "input",
        //     //sortable: true,
        //     overHidden: true,
        //     display: false
        //   },
        //   {
        //     label: "终端类型",
        //     prop: "rptNo",
        //     type: "select",
        //     overHidden: true,
        //     //sortable: true,
        //     search: true,
        //     searchOrder: 1,
        //     hide: true,
        //     display: false,
        //     rules: [
        //       {
        //         required: true,
        //         message: "请输入终端类型",
        //         trigger: "blur",
        //       },
        //     ],
        //     props: {
        //       label: 'rptName',
        //       value: 'rptNo',
        //       desc:'rptNo'
        //     },
        //     filterable: true,
        //     dicData: [],
        //     // change: (value) => {
        //     //   if (value) {
        //     //     // 获取供应商
        //     //     this.search.rpsNo = '';
        //     //     this.rpsNoList = [];
        //     //     this.search.rpmNo = '';
        //     //     this.rpmNoList = [];
        //     //     if (value.value) {
        //     //       getRpsNo(-1, -1, {rptNo: value.value}).then((res) => {
        //     //         this.rpsNoList = res.data.data.records;
        //     //         const column = this.findObject(this.option.column, "rpsNo");
        //     //         column.dicData = this.rpsNoList;
        //     //       })
        //     //     }
        //     //   }
        //     // }
        //   },
        //   {
        //     label: "供应商",
        //     prop: "rpsNo",
        //     type: "select",
        //     //sortable: true,
        //     search: true,
        //     searchOrder: 2,
        //     hide: true,
        //     filterable: true,
        //     display: false,
        //     rules: [
        //       {
        //         required: true,
        //         message: "请输入供应商名称",
        //         trigger: "blur",
        //       },
        //     ],
        //     props: {
        //       label: 'rpsName',
        //       value: 'rpsNo',
        //       desc:'rpsNo'
        //     },
        //     dicUrl: `/api/rb-service/service/terminal/terminal/supList?current=-1&size=-1`,
        //     dicFormatter:(data)=>{
        //       return data.data.records
        //     },
        //     // dicData: [],
        //     // change: (value) => {
        //     //   if (value) {
        //     //     // 获取型号
        //     //     this.search.rpmNo = '';
        //     //     this.rpmNoList = [];
        //     //     if (value.value) {
        //     //       getModelList(-1, -1, {rpmRpsNo: value.value}).then((res) => {
        //     //         this.rpmNoList = res.data.data.records;
        //     //         const column = this.findObject(this.option.column, "rpmNo");
        //     //         column.dicData = this.rpmNoList;
        //     //       })
        //     //     }
        //     //   }
        //     // }
        //   },
        //   {
        //     label: "型号",
        //     prop: "rpmNo",
        //     type: "select",
        //     search: true,
        //     searchOrder: 3,
        //     hide: true,
        //     display: false,
        //     filterable: true,
        //     rules: [
        //       {
        //         required: true,
        //         message: "请输入型号",
        //         trigger: "blur",
        //       },
        //     ],
        //     props: {
        //       label: 'rpmName',
        //       value: 'rpmNo',
        //       desc:'rpmNo'
        //     },
        //     dicUrl: `/api/rb-service/service/terminal/terminal/modelList?current=-1&size=-1`,
        //     dicFormatter:(data)=>{
        //       return data.data.records
        //     },
        //     // dicData: []
        //   },
          {
            label: "所属门店",
            prop: "storeName",
            type: "input",
            display: false,
            minWidth:180,
          },
          {
            label: "门店名称",
            prop: "storeNo",
            type: "select",
            search: true,
            searchOrder: 5,
            hide: true,
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入门店",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc:'rpsNo'
            },
            // dicUrl: `/api/rb-service/service/posStore/pos_store/listV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: [],
            change: (value) => {
              if (value) {
                this.search.rpstNo = ''; 
                this.rpstNoList = [];
                if (value.value) {
                  this.apiRpstList(value.value)
                }
              }
            }
          },
          {
            label: "所属收银员",
            prop: "rpstName",
            type: "input",
            display: false,
            width:140,
            overHidden:true
          },
          {
            label: "收银员名称",
            prop: "rpstNo",
            type: "select",
            search: true,
            searchOrder: 6,
            searchLabelWidth: 94,
            hide: true,
            filterable: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入收银员",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpstName',
              value: 'rpstNo',
              desc:'rpstNo'
            },
            // dicUrl: `/api/rb-service/service/posStaff/pos_staff/listV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: []
          },
          {
            label: "SN编号",
            prop: "rsSn",
            type: "input",
            //sortable: true,
            rules: [
              {
                required: true,
                message: "请输入SN编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "终端状态",
            prop: "isOn",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=is_on",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            display: false,
            rules: [
              {
                required: true,
                message: "请选择终端状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "绑定时间",
            prop: "createTime",
            type: "input",
            rules: [
              {
                required: true,
                message: "请输入创建时间",
                trigger: "blur",
              },
            ],
            display:false,
            overHidden: true,
            minWidth:140
          }
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      terminalDialog: {
        disabled: false,
        visible: false,
        type: 'add',
        text: '新建'
      },//表格右侧操作add,edit,view
      rpiNo: "",
      terminalDialogForm: { //终端表单
        id: '',
        aisleCode: '',
        rpiNo: '',
        rptNo: '',
        rpmNo: '',
        storeNo: '',
        rpstNo: '',
        rsSn: '',
        rtName: '',
        rtNo: '',
        rpsNo: ''
      },
      rptNoList: [],//类型
      rpsNoList: [],//供应商名称
      rpmNoList: [],//型号
      rpiNoList: [],//商户号
      storeNoList: [],//门店
      rpstNoList: [],//收银员
      hasPayPwd:false,
      twoPwdShow:false,
      towPwdForm:{
        towPwd:'',//二级密码
        rprNo:'',//终端的sn
        rpiNo:''//商户号
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.terminal_add, false),
        viewBtn: this.vaildData(this.permission.terminal_view, false),
        //delBtn: this.vaildData(this.permission.terminal_delete, false),
        editBtn: this.vaildData(this.permission.terminal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
  },
  created() {
    this.rpiNo = this.$route.query.rpiNo;
    // this.requestRptNo();
    this.apiStoreList();//获取门点
    this.apiRpstList();//获取收银员

    this.getUserHasInfo();//是否 有二级密码
  },
  methods: {
    // 解绑终端
    delJB(row){
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
        this.towPwdForm.rprNo = row.rsSn;
        this.towPwdForm.rpiNo = row.rpiNo;
        // this.towPwdForm.ids = row.id;
        this.twoPwdShow = true;
      }
      // this.$confirm("确定将选择数据解绑终端?", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(() => {
      //     let param ={
      //       rprNo:row.rsSn
      //     }
      //     return del(param);
      //   })
      //   .then((res) => {
      //     this.refreshChange();
      //     this.$message({
      //       type: "success",
      //       message: res.data.msg,
      //     });
      //   });
    },
    // 页面跳转
    toPage(row,type){
      if(type == "音响"){
        this.$router.push({ path: '/rb-service/posinfo/terminal/taika/sound',query:{ rpiNo: this.rpiNo,rprNo:row.rsSn,title:'音响',rptNo:'19'}})
      }else if(type == "打印机"){
        this.$router.push({ path: '/rb-service/posinfo/terminal/taika/printer',query:{ rpiNo: this.rpiNo,rprNo:row.rsSn,title:'打印机',rptNo:'17' }})
      }
    },
    // 二级密码 关闭回调
    handleCloseTwoPwd(done){
      this.towPwdForm.towPwd="";
      done()
    },
    // 二级密码 确定
    twoPwdSubmit(){
      let that = this;
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          let param ={
            rprNo:that.towPwdForm.rprNo,
            rpiNo:that.towPwdForm.rpiNo,
            payPwd:md5(that.towPwdForm.towPwd+'')
          }
           
          del(param).then((res) => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg
            });
            this.$refs.crud.toggleSelection();
            that.twoPwdShow = false;
            that.towPwdForm.towPwd="";
          });
        } else {
          return false;
         }
      });
    },
    // 是否 有二级密码
    getUserHasInfo(){
      userHasInfo().then(res =>{
        this.hasPayPwd = res.data.data.hasPayPwd;
      }, error => {
        window.console.log(error);
      })
    },
    // 跳转用户信息页面
    toUserInfo(){
      this.$confirm('请您先设置二级密码，再操作！', '提示', {
        confirmButtonText: '确定',
        showCancelButton:false,
        type: 'warning'
      }).then(() => {
        this.$router.push({ path: '/info/index', query: { index: 2 }})
      })
    },
    //查看二维码
    getqrCodeUrl(qrcodeUrl) {
      this.rqUrlImage[0] = qrcodeUrl;
      this.payVoucherDialog = true;
    },
    // 新建
    handleSave() {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'add';
      this.terminalDialog.text = "新增终端";
      this.terminalDialog.disabled = false;
    },
    // 编辑
    handleEdit(row) {
      let that = this;
      getDetail(row.id).then((res) => {
        that.terminalDialogForm = res.data.data;
        that.terminalDialog.visible = true;
        that.terminalDialog.type = 'edit';
        that.terminalDialog.text = "编辑终端";
        that.terminalDialog.disabled = true;
      });
    },
    handleView(row) {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'view';
      this.terminalDialog.text = "查看";
      this.terminalDialog.disabled = true;
      this.terminalDialogForm = JSON.parse(JSON.stringify(row));
    },
    /**
     * @func 终端状态开关
     * @desc 终端状态开关 0否 1是
     * @param {Object} row - 终端信息
     * */
    handleSwitch(row) {
      incomingTerminalOn(row.id, row.isOn).then(
        () => {},
        (error) => {
          row.isOn = row.isOn == 1 ? 0 : 1;
          window.console.log(error);
        }
      );
    },
    /* 新增终端 */
    rowSave(row, done, loading) {
      row.rpiNo = this.$route.query.rpiNo;
      addTerminal(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /* 修改终端 */
    rowUpdate(row, index, done, loading) {
      editTerminal(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
       this.towPwdForm.ids = row.id;
        this.twoPwdShow = true;
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      if(!this.hasPayPwd){
        this.toUserInfo();
      } else {
        this.towPwdForm.ids = this.ids;
        this.twoPwdShow = true;
      }
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getTerminalPage(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, { rpiNo: this.$route.query.rpiNo ,eqType:1,rptNo:23 })//,rpmNo:'R00001'
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.$emit('total');
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rtName=${this.search.rtName}`;
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      // exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&storeNo=${this.search.storeNo}`;
      exQuery += `&rpstNo=${this.search.rpstNo}`;
      exQuery += `&rtPara=${this.search.rtPara}`;
      exQuery += `&isOn=${this.search.isOn}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/terminal/terminal/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/terminal/terminal/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    // 终端---新建弹框 关闭前回调
    terminalDialogHandleClose(done) {
      this.$refs['terminalDialog'].initEmpty();
      done();
    },
    // 终端---新建弹框提交
    terminalDialogSubmit() {
      /**
       * add  新建
       * edit 修改
       * view 查看详情
       */
        this.$refs['terminalDialog'].$refs['terminalDialogForm'].validate((valid) => {
          let terminalDialogForm = this.$refs['terminalDialog'].terminalDialogForm;
          if (valid) {
            let param = {
              ...terminalDialogForm,
              rpiNo: this.rpiNo,
              // eqType:1 终端 （必传）
              rptNo:23//类型 （必传）
              // rpmNo:'R00001'//型号 （必传）
            }
            if (this.terminalDialog.type == 'add') {
              addTerminal(param).then(() => {
                  this.onLoad(this.page);
                  terminalDialogForm = {};
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  this.terminalDialog.visible = false;
                },
                (error) => {
                  window.console.log(error);
                }
              );
            } else if (this.terminalDialog.type == 'edit') {
              editTerminal(param).then(() => {
                  this.onLoad(this.page);
                  terminalDialogForm = {};
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  this.terminalDialog.visible = false;
                },
                (error) => {
                  window.console.log(error);
                }
              );
            }
          }
        });
    },
    // 获取 类型名称
    requestRptNo() {
      getRptNo(-1, -1).then((res) => {
        this.rptNoList = res.data.data.records;
        // const column = this.findObject(this.option.column, "rptNo");
        // column.dicData = this.rptNoList;
      })
    },
    // 获取 商户
    requestrpiNo() {
      getrpiNo(-1, -1).then((res) => {
        this.rpiNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpiNo");
        column.dicData = this.rpiNoList;
      })
    },
    // 获取 门店名称
    apiStoreList() {
      getstoreNo(-1, -1,{rpiNo:this.rpiNo}).then((res) => {
        this.storeNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "storeNo");
        column.dicData = this.storeNoList;
      })
    },
    // 获取 收银员名称
    apiRpstList(rpsNo = "") {
      let param ={};
      if(rpsNo){
        param.rpsNo = rpsNo;
      }
      getrpstNo(-1, -1, param).then((res) => {
        this.rpstNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpstNo");
        column.dicData = this.rpstNoList;
      })
    }
  }
};
</script>

<style>
</style>
